from fastapi import Request
from tortoise.transactions import in_transaction

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.token import Token
from util.str import Str

class Body:
    id: str
    title: str
    description: str

async def UpdateSongSheet(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            id = body.get("id")
            if Str.isBlank(id):
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            token = req.headers.get("token")
            if Token().verify_token(token) == None:
                return Result.error(BaseEnum.TOKEN_INVALID_ERROR)
            
            user = await UserService.getUserByToken(token)
            if user == None:
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
            
            title = body.get("title")
            description = body.get("description")

            sheet = await SongService.getSheetById(id)
            if sheet == None:
                return Result.error(BaseEnum.SONG_SHEET_NOT_EXIST_ERROR)
            if sheet.user_id != user.id:
                return Result.error(BaseEnum.USER_NO_SONG_SHEET_AUTHOR_ERROR)

            tmp = {
                "title": sheet.title if Str.isBlank(title) else title,
                "description": sheet.description if Str.isBlank(description) else description
            }

            res = await SongService.updateSongSheet(sheet.id, tmp)

            return Result.success(res)
    except Exception as e:
        Log.error('更新 song sheet 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)